class AttrItem extends eui.ItemRenderer {
	constructor() {
		super();
		this.skinName = 'attrItemSkinEx';
	}

	override childrenCreated(): void {
		super.childrenCreated();
		this.bindInput(this.value);
		this.bindInput(this.cbValue.input);
		this.cbValue.addEventListener(ComboBox.evtTextChange, this.onCBChange, this);
	}

	bindInput(input: eui.TextInput): void {
		input.textDisplay.addEventListener(egret.Event.CHANGE, this.onChange, this);
		input.textDisplay.addEventListener(MainFocus.inputEnterEvent, this.onInputEnter, this);
		input.textDisplay.addEventListener(MainFocus.inputTabEvent, this.onTab, this);
	}

	key: eui.Label;

	value: eui.TextInput;

	cbValue: ComboBox;

	lbStar: eui.Label;

	isnumber: boolean;

	protected override dataChanged(): void {
		const { data } = this;
		this.key.text = data.key;
		if (Array.isArray(data.value)) {
			// this.value.text = data.value[0];
			this.cbValue.setValues(data.value);
			// data.value = this.cbValue.input.text;

			this.cbValue.visible = true;
			this.value.visible = false;
		} else {
			this.value.text = data.value;
			this.cbValue.visible = false;
			this.value.visible = true;
		}
		// console.log("AttrItem",data.key,data.value)
		this.isnumber = false;
		if (typeof data.value === 'number') {
			// this.value.restrict = "0-9"
			this.isnumber = true;
		}
	}

	getValueText(): string {
		return this.cbValue.visible ? this.cbValue.input.text : this.value.text;
	}

	getValueNum(): number {
		const text = this.getValueText();
		const v = Number(text);
		if (!isNaN(v)) {
			return v;
		}
		return 0;
	}

	getValue(): number | string {
		const text = this.getValueText();
		if (this.isnumber) {
			const v = Number(text);
			if (!isNaN(v)) {
				return v;
			}
		}
		return text;
		// return this.isnumber ? Number(this.value.text) : this.value.text
	}

	onEnter(): void {
		const attr = this.data.attr as AttrCtrl;
		attr.onEnter(this);
		this.lbStar.visible = false;
	}

	onInputEnter(ev: egret.Event): void {
		const ev2: KeyboardEvent = ev.data;
		if (ev2.ctrlKey) {
			const file = this.getValueText();
			const json = `${getAssets() + file}.json`;
			const full = path.resolve(__dirname, json);
			if (fs.existsSync(full)) {
				MainFrame.ins().openAni(full);
			}
		} else {
			this.onEnter();
		}
	}

	onCBChange(): void {
		this.cbValue.closeDown();
		this.onEnter();
	}

	onChange(): void {
		this.lbStar.visible = true;
	}

	setValue(value: any): void {
		this.value.text = value;
		this.onChange();
	}

	onTab(ev: egret.Event): void {
		const shift = ev.data;
		const { attr } = this.data;
		attr.onTab(this, shift);
	}
}
